#include "stdafx.h"
#include "KeybdEvent2.h"

#define SHIFTED 0x80

void CKeybdEvent2::SingleStroke(HWND hWnd, WORD wVk, WORD wScan/* = 0*/)
{
	CKeybdEvent2 keybdEvent(hWnd, wVk, wScan);
}

void CKeybdEvent2::Combine2Strokes(HWND hWnd, WORD wVk1,WORD wVk2, WORD wScan1/* = 0*/, WORD wScan2/* = 0*/)
{
	BYTE rgbKeyState[256];
	::GetKeyboardState(rgbKeyState);
	{
		CKeybdEvent2 keybdEvent1(hWnd, wVk1, wScan1);
		rgbKeyState[wVk1] |= SHIFTED;
		::SetKeyboardState(rgbKeyState);
		{
			CKeybdEvent2 keybdEvent2(hWnd, wVk2, wScan2);
		}
	}
	rgbKeyState[wVk1] &= ~SHIFTED;
	::SetKeyboardState(rgbKeyState);
}

void CKeybdEvent2::Combine3Strokes(HWND hWnd, WORD wVk1, WORD wVk2, WORD wVk3, WORD wScan1/* = 0*/, WORD wScan2/* = 0*/, WORD wScan3/* = 0*/)
{
	BYTE rgbKeyState[256];
	::GetKeyboardState(rgbKeyState);
	{
		CKeybdEvent2 keybdEvent1(hWnd, wVk1, wScan1);
		rgbKeyState[wVk1] |= SHIFTED;
		::SetKeyboardState(rgbKeyState);
		{
			CKeybdEvent2 keybdEvent2(hWnd, wVk2, wScan2);
			rgbKeyState[wVk2] |= SHIFTED;
			::SetKeyboardState(rgbKeyState);
			{
				CKeybdEvent2 keybdEvent3(hWnd, wVk3, wScan3);
			}
		}
	}
	rgbKeyState[wVk2] &= ~SHIFTED;
	rgbKeyState[wVk1] &= ~SHIFTED;
	::SetKeyboardState(rgbKeyState);
}

SHORT CKeybdEvent2::VkKeyScan(TCHAR ch)
{
	HKL dwHkl = ::GetKeyboardLayout( ::GetCurrentThreadId() );

	return ::VkKeyScanEx(ch, dwHkl);
}

CKeybdEvent2::CKeybdEvent2(HWND hWnd, WORD wVk, WORD wScan/* = 0*/) : m_hWnd(hWnd), m_wVk(wVk), m_wScan(wScan)
{
	if(0 == m_wScan)
	{
		HKL dwHkl = ::GetKeyboardLayout( ::GetCurrentThreadId() ) ;
		m_wScan = (WORD)::MapVirtualKeyEx((UINT)wVk, 0, dwHkl);
	}

	DWORD dwRes = 0;
	::SendMessageTimeout(m_hWnd, WM_KEYDOWN, (WPARAM)m_wVk, (LPARAM)MAKELONG(0x0001, MAKEWORD(m_wScan, 0x00) ), SMTO_ABORTIFHUNG, 1000, &dwRes);
}

CKeybdEvent2::~CKeybdEvent2()
{
	DWORD dwRes = 0;
	::SendMessageTimeout(m_hWnd, WM_KEYUP, (WPARAM)m_wVk, (LPARAM)MAKELONG(0x0001, MAKEWORD(m_wScan, 0xC0) ), SMTO_ABORTIFHUNG, 1000, &dwRes);
}
